<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Programming in Lua : 11.1</title>
<link rel="stylesheet" type="text/css" href="pil.css">
</head>
<body>
<p class="warning">
<A HREF="contents.html"><IMG TITLE="Programming in Lua (first edition)" SRC="capa.jpg" ALT="" ALIGN="left"></A>This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.<BR>The third edition targets Lua 5.2 and is available at <A HREF="http://www.amazon.com/exec/obidos/ASIN/859037985X/theprogrammil3-20">Amazon</A> and other bookstores.<BR>By buying the book, you also help to <A HREF="../donations.html">support the Lua project</A>.
</p>
<table width="100%" class="nav">
<tr>
<td width="10%" align="left"><a href="11.html"><img border="0" src="left.png" alt="Previous"></a></td>
<td width="80%" align="center"><a href="contents.html"><font face="Helvetica,Arial,sanserif">
<font color="gray">Programming in </font><font color="blue"> Lua</font>
</font></a></td>
<td width="10%" align="right"><a href="11.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
<tr>
<td width="10%" align="left"></td>
<td width="80%" align="center"><a href="contents.html#P2">Part II. Tables and Objects</a>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<a href="contents.html#11">Chapter 11. Data Structures</a></td>
<td width="10%" align="right"></td></tr>
</table>
<hr/>
<p><h2>11.1 &ndash; Arrays</h2>

<p>We implement arrays in Lua simply by indexing tables with integers.
Therefore, arrays do not have a fixed size,
but grow as we need.
Usually, when we initialize the array we define
its size indirectly.
For instance, after the following code
<pre>
    a = {}    -- new array
    for i=1, 1000 do
      a[i] = 0
    end
</pre>
any attempt to access a field outside the range 1-1000
will return <B>nil</B>, instead of zero.

<p>
You can start an array at index 0, 1, or any other value:
<pre>
    -- creates an array with indices from -5 to 5
    a = {}
    for i=-5, 5 do
      a[i] = 0
    end
</pre>
However, it is customary in Lua to start arrays with index 1.
The Lua libraries adhere to this convention;
so, if your arrays also start with 1,
you will be able to use their functions directly.

<p>We can use constructors to create and initialize arrays in a
single expression:
<pre>
    squares = {1, 4, 9, 16, 25, 36, 49, 64, 81}
</pre>
Such constructors can be as large as you need
(well, up to a few million elements).

<hr/>
<table width="100%" class="nav">
<tr valign="top">
<td width="90%" align="left">
<small>
  Copyright &copy; 2003&ndash;2004 Roberto Ierusalimschy.  All rights reserved.
</small>
</td>
<td width="10%" align="right"><a href="11.2.html"><img border="0" src="right.png" alt="Next"></a></td>
</tr>
</table>


</body></html>

